import pymysql.cursors

# 采用 execute() 方法执行SQL 查询 SELECT
def insert_into_db(data):
    db = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='db_food'
    )
    # 采用 cursor 方法创建一个游标对象
    cursor = db.cursor()

    kind = data[0]
    food_name = data[1]
    energy = data[2]
    fat = data[3]
    sugar = data[4]
    protein = data[5]
    url = data[6]

    str = "INSERT INTO TB_FOOD(KIND,FOOD_NAME, ENERGY, FAT, SUGAR, PROTEIN, URL) \
    VALUES('%s','%s','%s','%s','%s','%s','%s')"
    print(str)
    print(data)
    try:
        # 执行sql语句
        cursor.execute(str % (kind, food_name, energy, fat, sugar, protein, url))
        # 提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        db.rollback()



    # 关闭数据库连接
    db.close()

    # place = "INSERT INTO TB_FOOD(KIND,FOOD_NAME, ENERGY, FAT, SUGAR, PROTEIN, URL) VALUES"
    #
    # sql = "(\""+kind+"\",\""+food_name+"\","+energy+","+fat+","+sugar+","+protein+",\""+url+"\")"
    # str = place + sql
    # print(str)
    # try:
    #     # 执行sql语句
    #     cursor.execute(str)
    #     # 提交到数据库执行
    #     db.commit()
    # except:
    #     # 如果发生错误则回滚
    #     db.rollback()
    #
    # cursor.execute(sql)
    #
    # # 关闭数据库连接
    # db.close()
